/*
 ============================================================================
 Name        : hev-main.c
 Author      : Heiher <admin@heiher.info>
 Version     : 0.0.2
 Copyright   : Copyright (c) 2010 everyone.
 Description : Linkage 802.1x for Unix-like operating system.
 ============================================================================
 */

#include <glib-object.h>

#include "hev-main.h"
#include "hev-server.h"

static void signal_handler(int signal)
{
	g_main_loop_quit(main_loop);
}

static void hev_server_real_state_changed(HevServer * server, gint state, gpointer data)
{
	switch(state)
	{
	case HEV_SERVER_NULL:
		break;
	case HEV_SERVER_FINDING_SERVER:
		g_message("Linkage4linux original by heiher.info.");
		g_message("Get source on http://code.google.com/p/linkage-4-linux/");
		g_message("Finding authentication server...");
		break;
	case HEV_SERVER_AUTH_ACCOUNT_NAME:
		g_message("Authenticating account name...");
		break;
	case HEV_SERVER_AUTH_ACCOUNT_PASSWD:
		g_message("Authenticating account password...");
		break;
	case HEV_SERVER_AUTH_SUCC:
		g_message("Authentication success, please start dhcp client now.");
		break;
	case HEV_SERVER_AUTH_FAIL_FINDING_SERVER:
		g_message("The server is refusing the request!");
		g_main_loop_quit(main_loop);
		break;
	case HEV_SERVER_AUTH_FAIL_ACCOUNT_NAME:
		g_message("Username incorrect!");
		g_main_loop_quit(main_loop);
		break;
	case HEV_SERVER_AUTH_FAIL_ACCOUNT_PASSWD:
		g_message("Password incorrect!");
		g_main_loop_quit(main_loop);
		break;
	case HEV_SERVER_AUTH_FAIL_SUCC:
		g_message("The server closed your connection.");
		break;
	case HEV_SERVER_TIMEOUT:
		g_message("Find server timeout!");
		g_main_loop_quit(main_loop);
		break;
	}
}

int main(int argc, char * argv[])
{
	g_type_init();

	main_loop = g_main_loop_new(NULL, FALSE);
	if(main_loop)
	{
		GObject * server = NULL;
		GError * error = NULL;

		signal(SIGKILL, signal_handler);
		signal(SIGINT, signal_handler);

		server = hev_server_new(NULL, &error);
		if(HEV_IS_SERVER(server))
		{
			g_signal_connect(G_OBJECT(server), "state_changed",
					G_CALLBACK(hev_server_real_state_changed), NULL);

			if(0 == hev_server_start(HEV_SERVER(server)))
			{
				g_main_loop_run(main_loop);
				hev_server_stop(HEV_SERVER(server));
			}

			g_object_unref(server);
		}
		else
		{
			g_critical("[%s -> hev_server_new]: %s", __FUNCTION__, error->message);
			g_error_free(error);
		}

		g_main_loop_unref(main_loop);
	}

	return 0;
}
